<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="开具证明" :showBack="true"></pageHeaderNew>
    </template>
    <div style="display: flex; justify-content: center">
      <a-steps :current="step" style="width: 600px; margin: 20px">
        <a-step>基本信息</a-step>
        <a-step>预览开具信息</a-step>
        <a-step v-if="formData.isApprove === 1">选择审批流程</a-step>
      </a-steps>
    </div>
    <div class="step1" v-show="step === 1">
      <a-form :model="formData" style="width: 500px" auto-label-width>
        <a-form-item label="开具证明类型" required>
          <a-select
            v-model="formData.type"
            @change="
              () => {
                formData.typeName = formData.type === 2 ? 7 : 5;
                formData.templateId = undefined;
              }
            "
          >
            <a-option
              v-for="(item, index) in ['实习', '离职', '工作', '收入']"
              :key="index"
              :value="index + 1"
            >
              {{ item }}证明
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="开具证明员工" required>
          <HumanMultipleModal
            ref="refHumanMultipleModal"
            :disabled="formData.disabled"
            :typeName="[formData.typeName as number]"
            v-model:values="formData.userIds"
          />
        </a-form-item>
        <a-form-item label="选择开具证明模板" required>
          <a-select v-model="formData.templateId" @change="templateChange">
            <a-option
              v-for="item in internshipProofList[(formData.type || 0) - 1]
                ? internshipProofList[(formData.type || 0) - 1].content
                : []"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
      </a-form>
      <div
        class="htmlBox"
        v-html="templateData.text"
        :style="{
          width: templateData.direction === 1 ? '555px' : '802px',
          height: templateData.direction === 1 ? '802px' : '555px'
        }"
      />
      <!-- <div>
        <a-button type="primary" @click="nextStep">下一步</a-button>
      </div> -->
    </div>
    <Step2
      ref="refStep2"
      v-show="step === 2"
      :direction="templateData.direction"
      :isApprove="formData.isApprove"
      @back="() => step--"
      @nextStep="() => step++"
    />
    <footer>
      <a-space>
        <a-button v-show="step > 1" @click="() => step--" class="btn"
          >上一步</a-button
        >
        <a-button
          type="primary"
          @click="nextStep"
          class="btn"
          v-if="
            (step < 3 && formData.isApprove === 1) ||
            (step === 1 && formData.isApprove === 2)
          "
          >下一步</a-button
        >
        <a-button type="primary" @click="submit" class="btn" v-if="step === 3"
          >提交</a-button
        >
        <a-button
          type="outline"
          @click="toPrint"
          class="btn"
          v-show="formData.isApprove === 2 && step === 2"
          >打印</a-button
        >
        <a-button
          type="primary"
          @click="download"
          class="btn"
          v-show="formData.isApprove === 2 && step === 2"
          >下载</a-button
        >
      </a-space>
    </footer>
  </ContentCard>
</template>

<script setup lang="ts">
import HumanMultipleModal from '@/components/HumanMultipleModal/index.vue';
import { GetBusinessModalData } from '@/apis/controltotal';
import Step2 from './Step2.vue';
import { GetInternshipProofTemplate } from '@/apis/management/human/baseSetting/certificateSetting';
import { Message } from '@arco-design/web-vue';
import { getHumanDetail } from '@/utils/common';

let formData = reactive<{
  type?: number;
  typeName?: number;
  disabled?: boolean;
  templateId?: number;
  isApprove: 1 | 2; // 模板是否有审批 1 有 2 无
}>({
  userIds: [localStorage.getItem('userId')],
  typeName: 5,
  disabled: true,
  isApprove: 1
});

let refHumanMultipleModal = ref();
let refStep2 = ref();
let nextStep = async () => {
  if (!formData.templateId) return Message.error('请选择模板');
  if (!formData.userIds.length) return Message.error('请选择人员');
  // let choideList = refHumanMultipleModal.value.getChoiceList();
  let choideList = await getHumanDetail(formData.userIds[0]);
  choideList = [choideList];
  // if (
  //   formData.type === 2 &&
  //   choideList.every(({ progress }: any) => progress !== 7)
  // )
  //   return Message.error('离职证明必须选择已离职人员');
  refStep2.value.setUsers(
    choideList.map(({ id, name }: any) => {
      return {
        id,
        name
      };
    }),
    formData.templateId
  );
  step.value++;
};

let route = useRoute();
let templateData = computed(() => {
  if (!formData.type || !formData.templateId) return { test: '' };
  let text = '';
  let item = internshipProofList.value[(formData.type || 0) - 1].content.find(
    ({ id }: any) => id === formData.templateId
  );
  text = item.text;
  fieldList.value.forEach(({ ctlCode, ctlCnName }) => {
    text = text.replaceAll(ctlCode, ctlCnName);
  });
  return { text, direction: item.direction };
});

//模板信息
let internshipProofList = ref<any[]>([]);
//字段信息
let fieldList = ref<any[]>([]);
let loadData = async () => {
  try {
    let data = JSON.parse(route.query.jsonStr + '');
    formData.type = data.type;
    formData.typeName = formData.type === 2 ? 7 : 5;
    formData.userIds = data.userIds;
    formData.disabled = !!data.disabled;
  } catch (err) {
    //
  }
  let pageData = { pageNumber: 0, pageSize: 20 };
  let res = await Promise.all([
    GetInternshipProofTemplate({ ...pageData, type: 1 }),
    GetInternshipProofTemplate({ ...pageData, type: 2 }),
    GetInternshipProofTemplate({ ...pageData, type: 3 }),
    GetInternshipProofTemplate({ ...pageData, type: 4 })
  ]);
  internshipProofList.value = res;
  const { funcCtlInfos }: any = await GetBusinessModalData({
    funcCode: 'SER_FUNC9B158E4240DE49979E62895D0AEF9080'
  });
  funcCtlInfos.children.forEach(({ subDetail }: any) => {
    subDetail?.subRelDetail?.forEach(({ ctlCode, ctlCnName }: any) => {
      fieldList.value.push({ ctlCode, ctlCnName });
    });
  });
};
loadData();

let step = ref(1);

const templateChange = (id: number) => {
  const { approve } = internshipProofList.value[
    formData?.type - 1
  ].content.find((item: any) => item.id === id);
  formData.isApprove = approve;
};

// 打印
const toPrint = () => {
  refStep2.value.toPrint();
};

// 下载;
const download = () => {
  refStep2.value.download();
};
</script>

<style scoped>
.step1 {
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  align-items: center;
}
.htmlBox {
  width: 555px;
  padding: 20px;
  height: 802px;
  word-wrap: break-word;
  box-shadow: 0px 0px 10px var(--color-neutral-8);
  margin-top: 40px;
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
</style>
